<template>
  <globalModal :title="title" :visible="visible" :confirmLoading="confirmLoading" @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" autocomplete="off" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-form-item label="姓名" :validateStatus="validateNameStatus" help="姓名不能包含特殊字符且不超过16个英文字符，8个汉字">
          <a-input
            placeholder="请输入姓名"
            @blur="validateName"
            v-decorator="[
              'realName',
              {
                rules: [{ required: true, whitespace: true, message: '请输入姓名' }],
                getValueFromEvent: spliceStudName,
              },
            ]"
          />
        </a-form-item>
        <template v-if="false">
          <a-form-item label="所属医院" v-if="isAdmin">
            <a-input
              placeholder="请选择所属医院"
              v-decorator="[
                'deptId',
                {
                  rules: [{ required: true, message: '请选择所属医院' }],
                },
              ]"
              readOnly
              style="display: none"
            />

            <span class="ant-input-group-wrapper">
              <span class="ant-input-wrapper ant-input-group">
                <input v-model="deptName" placeholder="请选择所属医院" type="text" readonly="true" class="ant-input" />
                <span class="ant-input-group-addon"> <a-icon @click="changeDept" slot="addonAfter" type="setting" style="cursor: pointer" /></span>
              </span>
            </span>
          </a-form-item>
          <a-form-item label="随访医生">
            <a-input
              placeholder="请选择随访医生"
              v-decorator="[
                'doctorId',
                {
                  rules: [{ required: true, message: '请选择随访医生' }],
                },
              ]"
              readOnly
              style="display: none"
            />
            <span class="ant-input-group-wrapper">
              <span class="ant-input-wrapper ant-input-group">
                <input v-model="doctorName" placeholder="请选择随访医生" type="text" readonly="true" class="ant-input" />
                <span class="ant-input-group-addon"><a-icon @click="changeDept" slot="addonAfter" type="setting" style="cursor: pointer" /></span>
              </span>
            </span>
          </a-form-item>
        </template>
        <a-form-item label="手机号码">
          <a-input
            placeholder="手机号码"
            v-decorator="[
              'phone',
              {
                rules: [
                  { required: true, message: '请输入手机号码' },
                  {
                    validator: validatePhone,
                  },
                ],
                trigger: 'blur',
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="性别">
          <a-radio-group v-decorator="['gender', { rules: [{ required: true, message: '请选择性别' }] }]">
            <a-radio value="男">男</a-radio>
            <a-radio value="女">女</a-radio>
          </a-radio-group>
        </a-form-item>
        <!-- <a-form-item label="病人等级">
					<a-radio-group v-decorator="['sickerGrade']">
						<a-radio :value="item.itemCode" v-for="(item, index) in sickerrGrade" :key="index">{{
							item.itemName
						}}</a-radio>
					</a-radio-group>
				</a-form-item> -->
        <a-form-item label="病人等级">
          <!-- <a-radio-group v-decorator="['illnessGrade']">
						<a-radio :value="item.itemCode" v-for="(item, index) in illnessGrade" :key="index">{{
							item.itemName
						}}</a-radio>
					</a-radio-group> -->
          <!-- <a-select
					    mode="multiple"
					    v-decorator="['illnessGrade']"
					    style="width: 100%"
					    placeholder="请选择病人等级" @change="changeillnessGrade"
					  >
					    <a-select-option :disabled="filterIsdisabled(item.itemCode,item.itemName)" :value="item.itemCode"  v-for="(item, index) in illnessGrade" :key="index">
					      {{
					      	item.itemName
					      }}
					    </a-select-option>
					  </a-select> -->
          <a-select
            mode="multiple"
            v-decorator="['illnessGrade']"
            style="width: 100%"
            :options="filteredOptions"
            placeholder="请选择病人等级"
            @change="changeillnessGrade"
          >
          </a-select>
        </a-form-item>
        <a-form-item label="身份证号">
          <a-input
            placeholder="身份证号"
            v-decorator="[
              'identityCard',
              {
                rules: [
                  { required: true, message: '请输入身份证号' },
                  {
                    validator: validateIdCard,
                  },
                ],
                trigger: 'blur',
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="出生日期">
          <j-date
            class="w100"
            v-decorator="['birth', { rules: [{ required: true, message: '请输入出生日期' }] }]"
            placeholder="请选择出生日期"
            date-format="YYYY-MM-DD"
          ></j-date>
        </a-form-item>

        <a-form-item label="地址">
          <a-textarea placeholder="地址" v-decorator="['address']" />
        </a-form-item>
        <a-form-item label="备注">
          <a-textarea placeholder="备注" v-decorator="['remark']" />
        </a-form-item>
      </a-form>
    </a-spin>
    <template slot="footer">
      <div class="my-modal-footer">
        <a-button class="ant-btn-cancel" @click="handleCancel">取消</a-button>
        <a-button type="primary" class="ant-btn-ok" @click="handleOk">确定</a-button>
      </div>
    </template>
    <change-dept-modal ref="changeDeptModal" @selectDept="selectDept"></change-dept-modal>
  </globalModal>
</template>

<script>
import { patientManageapi } from "@/api/index.js";
import { ModalMixins } from "@/mixins";
import changeDeptModal from "@/components/changeDeptModal.vue";
import { getBytesLength } from "@/utils/base.js";
import JDate from "@/components/JDate";
const reg = /^[A-Za-z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?|\u4e00-\u9fbb|\\！|\\，|\\。|\\（|\\）|\\《|\\》|\\“|\\”|\\？|\\：|\\；|\\【|\\】|\\……|\\￥]+$/;
export default {
  name: "AddOrEditStuModal",
  mixins: [ModalMixins],
  data() {
    return {
      deptName: "",
      validateNameStatus: "",
      sickerrGrade: [], // 患者等级
      illnessGrade: [], // 疾病等级
      doctorName: "",
      doctor: {},
      selectedDiseases: [],
    };
  },
  components: { changeDeptModal, JDate },
  created() {
    this.getDictItemKeyList(["SICKERR_GRADE", "ILLNESS_GRADE"]);
  },
  computed: {
    // 过滤后的选项，已选择同类型疾病的禁用其他等级
    filteredOptions() {
      const selectedTypes = this.selectedDiseases.map((val) => val.split("_")[0]);

      return this.illnessGrade.map((option) => {
        const optionType = option.value.split("_")[0];
        return {
          ...option,
          disabled: selectedTypes.includes(optionType) && !this.selectedDiseases.includes(option.value),
        };
      });
    },
  },
  methods: {
    compareName(rule, value, callback) {
      const form = this.form;
      if (value) {
        if (getBytesLength(value) > 16) {
          // 正则验证
          callback("姓名不超过16个英文字符，8个汉字"); // 校验未通过
        } else if (!reg.test(value)) {
          callback("姓名不能包含特殊字符"); // 校验未通过
        }
      }
      callback();
    },
    initInfo(record = {}) {
      if (this.isAdd) {
        this.mdl = Object.assign(record, {
          gender: "男",
        });
        this.doctor = record;
      } else {
        this.mdl = Object.assign(record);
      }
      this.title = (this.isAdd ? "新增" : "编辑") + this.modalTitle;
      this.visible = true;
      // 获取一些初始下拉数据
      this.getDefaultList && this.getDefaultList();
    },
    async getDefaultList() {
      this.deptName = this.mdl.deptName || "";
      this.doctorName = this.mdl.realName || "";
      this.$nextTick(() => {
        this.form.resetFields();
        this.setFieldsValue();
      });
    },
    setAddFieldsValue() {
      if (this.mdl && Object.keys(this.mdl).length > 0) {
        this.form.setFieldsValue(this.$pick(Object.assign({}, this.mdl), "deptId", "doctorId", "gender"));
      }
    },

    changeDept(value) {
      if (this.isAdmin && !this.globalOrgId) {
        this.$message.error("请先选择一个机构");
        return false;
      }
      this.$refs.changeDeptModal.show(this.globalOrgId);
    },
    selectDept(dept) {
      this.deptName = dept.deptName;
      this.$nextTick(() => {
        this.form.setFieldsValue({
          deptId: dept.deptId,
          gradeId: undefined,
          classId: undefined,
        });
        this.getGradeList(dept.deptId);
        this.classList = [];
        this.changeGrade({ e: { target: { value: undefined } } });
      });
    },
    validateUserName(rule, value, callback) {
      if (value) {
        if (!this.isAdd) {
          callback();
        } else if (/^[0-9a-zA-Z]+$/.test(value)) {
          callback();
        } else {
          callback("账号只能由数字、字母组成");
        }
      } else {
        callback();
      }
    },
    validatePhone(rule, value, callback) {
      if (value) {
        if (this.oldphone == value) {
          callback();
        } else if (/^1[0-9]{10}$/.test(value)) {
          callback();
        } else {
          callback("请输入正确的手机号码");
        }
      } else {
        callback();
      }
    },
    validateIdCard(rule, value, callback) {
      const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (value) {
        if (!reg.test(value)) {
          callback("请输入有效的身份证号码");
        } else {
          const birthDate = value.substring(6, 14);
          const year = birthDate.substring(0, 4);
          const month = birthDate.substring(4, 6);
          const day = birthDate.substring(6, 8);
          const formattedBirthDate = `${year}-${month}-${day}`;
          this.form.setFieldsValue({ birth: formattedBirthDate });
          callback();
        }
      } else {
        callback();
      }
    },
    // 查询有效期
    getDictItemKeyList(keys) {
      var param = keys;
      this.$postAction(this.$sysManageapi.dictUrl.getDictItemKeyList, param).then((res) => {
        if (res.code == 1) {
          if (res.data.SICKERR_GRADE) {
            this.sickerrGrade = res.data.SICKERR_GRADE;
          }
          if (res.data.ILLNESS_GRADE) {
            this.illnessGrade = res.data.ILLNESS_GRADE.map((item) => {
              return {
                value: item.itemCode,
                label: item.itemName,
              };
            });
          }
        }
      });
    },
    // 切换病人等级
    changeillnessGrade(selectedValues) {
      // 获取新选择的疾病类型和等级
      const newSelections = selectedValues.filter((val) => !this.selectedDiseases.includes(val));

      if (newSelections.length > 0) {
        const newValue = newSelections[0];
        const diseaseType = newValue.split("_")[0]; // 获取疾病类型

        // 过滤掉同类型疾病的其他等级
        this.selectedDiseases = [...this.selectedDiseases.filter((val) => !val.startsWith(diseaseType + "_")), newValue];
      } else {
        this.selectedDiseases = selectedValues;
      }
    },
    handleOk() {
      if (this.validateNameStatus == "error") {
        return;
      }
      const _this = this;
      // 触发表单验证
      this.form.validateFields((err, values) => {
        console.log("err", err);
        // 验证表单没错误
        if (!err) {
          console.log("val", values);
          const parameter = Object.assign(
            {
              orgId: this.globalOrgId,
              deptId: this.doctor.deptId,
              doctorId: this.doctor.doctorId,
            },
            values,
            this.mdl.studId ? { studId: this.mdl.studId } : ""
          );
          if (parameter.birth) {
            parameter.birth = parameter.birth + " 00:00:00";
          }
          if (parameter.illnessGrade) {
            parameter.illnessGrade = parameter.illnessGrade.join(",");
          }
          _this.confirmLoading = true;
          this.$postAction(_this.isAdd ? patientManageapi.patientUrl.add : patientManageapi.patientUrl.edit, parameter)
            .then((res) => {
              if (res && res.code == 1) {
                _this.$message.success("保存成功");
                _this.$emit("ok", _this.isAdd);
                _this.form.resetFields();
                this.handleCancel();
              }
            })
            .finally(() => {
              _this.confirmLoading = false;
            });
        } else {
        }
      });
    },
    handleCancel() {
      this.confirmLoading = false;
      this.$emit("close");
      this.visible = false;
      this.dayclassList = [];
      this.deptName = "";
      this.selectedDiseases = [];
    },
    validateName(e) {
      this.validateNameStatus = !e.target.value || getBytesLength(e.target.value) > 16 || !reg.test(e.target.value) ? "error" : "";
    },
    spliceStudName(e) {
      const value = e.target.value.trim();
      if (!value) {
        this.validateNameStatus = "error";
        return "";
      }
      if (getBytesLength(value) > 16 || !reg.test(value)) {
        this.validateNameStatus = "error";
        const arr = [];
        let num = 0;
        for (var i = 0; i < value.length; i++) {
          if (reg.test(value[i])) {
            num = num + getBytesLength(value[i]);
            if (num <= 16) {
              arr.push(value[i]);
            }
          }
        }
        return arr.join("");
      } else {
        this.validateNameStatus = "";
        return value;
      }
    },
  },
};
</script>
